import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


@WebServlet("/get_ai_painting")
public class GetAIPainting extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        String id = req.getParameter("id");
        if (id == null) {
            throw new ServletException("please input id");
        }

        String painId = getPaintId(conn, id);

        AIPaintingEngine engine = new AIPaintingEngine();
        String url = engine.get(painId);
        if (url.isEmpty()) {
            PrintWriter out = resp.getWriter();
            out.print("正在创作中，请稍后重试...");
            out.close();
        } else {
            resp.sendRedirect(url);
        }
    }

    public static String getPaintId(final Connection conn, String id) throws ServletException {
        Statement stmt = null;
        ResultSet rs = null;
        String paintId = "";
        try {
            stmt = conn.createStatement();
            String sql = String.format("SELECT paint_id FROM t_ai_painting WHERE id = '%s'", id);
            rs = stmt.executeQuery(sql);

            if (rs.next()) {
                do {
                    paintId = rs.getString("paint_id");
                } while (rs.next());
            } else {
                throw new ServletException("prompt info not exist");
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            try {
                rs.close();
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return paintId;
    }

}
